﻿<?php
/**
 * Login Controller
 *
 * Sewiki is a experimental software for course
 * Software Engineering in HIT and it's devoloped
 * upon CodeIgniter Framework. More infomation of
 * the framework, please vist http://codeigniter.com/
 *
 * @package  : CodeIgniter
 * @category : controller/user
 * @author   : Oneplus <oneplus.lau@gmail.com>
 * @date     : 2011-06-13
 */
class Login extends CI_Controller {
	/**
	 * The constructor
	 *
	 * @access : public
	 * @return : void
	 */
	function __construct() {
		parent::__construct();
		$this->load->database();
	}
	
	public function index() {
		$this->login();
	}
	
	public function login() {
		$this->load->view('user/login');
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		
		if($this->input->post('login')) {
			if($this->check($username, $password) == true) {
				redirect('main');
			}
			else {
				redirect('user/login/');
			}
		}
	}
	
	public function logout() {
		$data = array(
			'uid'       => '',
			'role'      => '',
			'logged_in' => '');
		$this->session->unset_userdata($data);
		redirect('main');
	}
	
	public function welcome() {
		if($this->session->userdata('logged_in') == false) {
			redirect('system/login');
		}
		
		$uid      = $this->session->userdata('uid');
		$user     = $this->db->get_where('users', array('uid' => $uid));
		$username = $user->row()->username;
		$data = array(
			'username' => $username,
			'role'     => $this->session->userdata('role'));

		$this->load->view('system/welcome', $data);
	}
	
	private function check($usr, $pwd) {
		$this->load->model('user');
		$user = $this->user->login($usr, $pwd);

		if(isset($user['uid']) == true) {
			$sessiondata = array(
				'uid'       => $user['uid'],
				'role'      => $user['role'],
				'logged_in' => true);

			$this->session->set_userdata($sessiondata);
			
			$sessiondata = array(
				'login_error' => '');
			
			$this->session->unset_userdata($sessiondata);
			return true;
		}
		else {
			$sessiondata = array('msg' => '用户名或密码错误');
			$this->session->set_userdata($sessiondata);
			return false;
		}
	}
}
?>
